<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/11 0011
 * Time: 上午 10:40
 */

namespace api\controllers;


use api\behaviors\RedisBehavior;
use api\event\xhprofEvent;
use common\config\AppConf;
use common\helpers\StringHelper;
use common\models\base\BaseModel;
use Yii;
use yii\data\ActiveDataProvider;
use yii\filters\auth\QueryParamAuth;
use yii\helpers\ArrayHelper;
use yii\rest\ActiveController;


class BaseController extends ActiveController
{
    public $_data = [];
    public $searchModelClass = '';

    public function init()
    {
        parent::init();

        //xhprof不使用请关闭
        if (YII_DEBUG && YII_ENV == 'dev') {
//            $xhprof = new xhprofEvent();
//            $this->on(self::EVENT_BEFORE_ACTION, [$xhprof, 'xhprofStart']);
//            $this->on(self::EVENT_AFTER_ACTION, [$xhprof, 'xhprofEnd']);
        }
    }


    public function actions()
    {
        $actions = parent::actions();

        // 禁用"delete" 和 "create" 动作
        unset($actions['delete']);

        // 使用"prepareDataProvider()"方法自定义数据provider
        $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];

        return $actions;
    }

    public function prepareDataProvider()
    {
        //构建load需要的一个查询参数数组，以model的名称为键
        $search_model_name = StringHelper::getModelClassName($this->modelClass . 'Search');
        //新建searchModel,获得dataProvider
        $searchModel = Yii::createObject([
            'class' => $this->searchModelClass,
        ]);

        $searchModel->status = BaseModel::STATUS_ACTIVE;
        $qparams = Yii::$app->getRequest()->getQueryParams();

        //这是为load做准备的，相当于给model传参，但是要按照这种格式
        $params[$search_model_name] = $qparams;

        //search方法其实可以增加自定义分页属性的功能
        /** @var ActiveDataProvider $dataProvider */
        $dataProvider = $searchModel->search($params);
        return $dataProvider;
    }

    /**
     * 用来验证
     * @return array
     */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticatior' => [
                'class' => QueryParamAuth::className(),//此类中可以修改url中access-token键名
                'tokenParam' => 'access_token',
            ],
//            'redisIp' => [
//                'class' => RedisBehavior::className()
//            ]
        ]);
    }

    /**
     * 把分页这些信息放到response里，相当于把list放到了rspdata里
     * @var array
     */
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => AppConf::APP_DATA,
    ];

    /*单字段*/
    public function addDiyData($key, $value)
    {
        $data[$key] = $value;
        $this->_data = $this->_data ? array_merge($this->_data, $data) : $data;
    }

    /*集合*/
    public function addData($data)
    {
        $this->_data = $this->_data ? array_merge($this->_data, $data) : $data;
    }

    /**
     * @param $data :如果data有值，则只传输data里的值，如果data无值，则传输addData/addDiyData里的值
     * @param string $message
     * @param int $code
     * @return array
     */
    public function renderJson($data = [], $code = AppConf::APP_NO_OK, $message = 'ok')
    {
        if (!empty($data)) {
            $this->_data = $data;
        }

        return [
            AppConf::APP_DATA => $this->_data,
            AppConf::APP_NO => $code,
            AppConf::APP_MSG => $message
        ];
    }

    /**
     * 错误提示的时候
     * @param int $code
     * @param string $message
     * @return array
     */
    public function renderError($code = AppConf::APP_NO_OK, $message = 'ok')
    {
        return $this->renderJson([], $code, $message);
    }
}